<template>
  <div
    ref="teldCommentRef"
    class="teld-comment w-full h-full teld-color-black flex flex-col relative text-sm"
  >
    <div
      v-if="showHeader && showHeader !== 'false'"
      class="comment-header px-5 py-4 flex justify-between items-center text-base"
    >
      <!-- 评论标题 -->
      <div
        :title="commentTitle"
        class="comment-header__title flex-1 mr-3 truncate truncate-line-2"
      >
        {{ commentTitle }}
      </div>
      <div class="comment-header__count teld-color-gray text-sm">
        {{ qLangComment.funcCommentCount(totalCommentCount) }}
      </div>
    </div>
    <!-- 评论内容滚动区域 -->
    <div
      ref="commentScrollAreaRef"
      class="flex-1 overflow-y-auto outline-none w-full"
    >
      <div
        v-for="comment in commentList"
        :key="comment.ID"
        class="section-comment-with-replies flex px-5 py-3 border-b border-solid border-gray-100"
      >
        <!-- 左侧头像 -->
        <div class="left-avatar mr-2" style="">
          <UserAvatar :image-url="comment.UserAvatar" />
        </div>

        <!-- 右侧内容 -->
        <CommentItem
          :data-item="comment"
          @increase="totalCommentCount += 1"
          @decrease="n => (totalCommentCount -= n || 1)"
        />
      </div>

      <template v-if="!isLoading && !commentList.length">
        <template v-if="$slots && $slots.empty">
          <slot name="empty"></slot>
        </template>
        <div
          v-else
          class="teld-comment--empty relative"
          style="top: 50%; margin-top: -50%"
        >
          <div class="teld-color-gray flex justify-center items-center h-20">
            <!-- {{ $commentOptions.emptyText || `暂无数据` }} -->
            <NoData
              :text="emptyText || qLangComment.noData"
            ></NoData>
          </div>
        </div>
      </template>
    </div>

    <!-- 评论输入框 -->
    <draft-editor
      ref="draftEditorRef"
      :visible="!isLoading && visible"
      :show-avatar="false"
      :input-indicator="true"
      :is-comment="true"
      :auto-clear-on-hidding="false"
      :placeholder="qLangComment.commentPlaceholder"
      class=""
      @comment="onComment"
    />

    <!-- loading -->
    <t-inner-loading :showing="isLoading">
      <t-spinner size="28px" color="primary" />
    </t-inner-loading>
  </div>
</template>

<script>
// Commponents
import DraftEditor from './draft-editor/index.vue';
import CommentItem from './comment-item/index.vue';
import UserAvatar from '../components/user-avatar/index.vue';
import NoData from 't/bussiness/repeat/no-data.vue';

// Utils
import { scrollPaging } from '../hooks';
import { getCommentList, saveComment } from '../hooks/api';
import { COMMENT_TYPE } from '../utils';

// import '../assets/vant-override.css';
import '../assets/style-mobile.scss';

export default {
  name: 'CommentMobile',
  // inject: ['pageUrl', 'notificationLink'],
  inject: [
    'qLangComment',
    'dense',
    'loginUserInfo',
    'notificationLink',
  ],
  props: {
    /**
     * 是否显示顶部评论标题和总条数
     */
    showHeader: {
      type: [Boolean, String],
      default: false,
    },
    pageId: {
      type: String,
      default: '',
    },
    dataId: {
      type: String,
      default: '',
    },
    /**
     * 维度
     */
    dimension: {
      type: String,
      default: '',
    },
    commentType: {
      type: Number,
      default: COMMENT_TYPE.DataComment,
    },
    commentTitle: {
      type: String,
      default: '',
    },
    commentReference: {
      type: String,
      default: '',
    },
    /**透传visible用于点开时给editor赋焦点*/
    visible: {
      type: Boolean,
      default: false,
    },
    /* 无数据时提示文字 */
    emptyText: {
      type: String,
      default: '',
    },
  },
  components: {
    DraftEditor,
    CommentItem,
    UserAvatar,
    NoData,
  },
  data() {
    return {
      commentList: [],
      totalCommentCount: 0,
      isLoading: false,
      hasLoadedAll: false,
      pageIndex: 1,
      pageSize: 20,
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.init();
      } else {
        this.reset();
      }
    },
  },
  created() {
    this.init();
  },
  mounted() {
    const scrollArea = this.$refs.commentScrollAreaRef;
    if (scrollArea) {
      scrollArea.addEventListener('wheel', this.onScroll, true);
    }
  },
  beforeDestroy() {
    const scrollArea = this.$refs.commentScrollAreaRef;
    scrollArea && scrollArea.removeEventListener('wheel', this.onScroll);
  },
  methods: {
    async fetchPageData() {
      this.isLoading = true;
      try {
        const payload = {
          PageID: this.pageId,
          DataID: this.dataId,
          // DataName: this.commentTitle,
          Dimension: this.dimension,
          PageIndex: this.pageIndex,
          PageCount: this.pageSize,
          Sort: 0, // 评论-倒序
        };
        const listRes = await getCommentList(payload);
        if (!listRes || listRes.state !== '1' || !listRes.data) {
          // 获取数据失败
          return;
        }

        // 成功获取数据后
        const { Items, TotalCount, Properties } = listRes.data;
        this.commentList = this.commentList.concat(Items);
        this.totalCommentCount =
          (Properties && Properties.UICount) || TotalCount;
        this.pageIndex += 1;
        this.hasLoadedAll = this.commentList.length >= TotalCount;
      } catch (error) {
        console.log(error);
      } finally {
        setTimeout(() => {
          this.isLoading = false;
        }, 500);
      }
    },
    init() {
      if (!this.pageId) {
        throw new Error('pageId is required');
      }
      if (this.commentType == COMMENT_TYPE.DataComment && !this.dataId) {
        throw new Error('dataId is required when commentType is 0.DataComment');
      }
      this.fetchPageData();
    },
    reset() {
      this.commentList = [];
      this.totalCommentCount = 0;
      this.pageIndex = 1;
      const container = this.$refs.commentScrollAreaRef;
      if (container) {
        container.scrollTop = 0;
      }
    },
    async onComment(draftInfo) {
      const { content, fileList, onSucceed, onFail } = draftInfo;

      const newComment = {
        // IsAuthor: true,
        // 接口需要的参数：
        Content: content,
        Dimension: this.dimension, //
        PageID: this.pageId,
        DataID: this.dataId,
        DataName: this.commentTitle,
        ReferenceTitle: this.commentReference,
        CommentType: this.commentType,
        CommentCategory: 0,
        Attachments: fileList.map(n => n.result),
        UserAvatar: this.loginUserInfo.avatar,
        Url: this.notificationLink(),
        UrlParams: JSON.stringify({
          // fpath: encodeURIComponent(this.pageUrl),
          showComment: true,
        }),
      };

      try {
        const res = await saveComment(newComment);
        console.log('SaveComment', res);

        if (!res || res.state !== '1' || !res.data) {
          onFail();
          return;
        }

        // mock new record, and override with real data
        Object.assign(
          newComment,
          {
            ID: 'comment-m-' + parseInt(Math.random() * 1000),
            CommentTime: Date().toLocaleString(),
            UserID: this.loginUserInfo.userId,
            UserName: this.loginUserInfo.userName,
            Liked: false,
            LikeCount: 0,
            IsFavorite: false,
            FavoriteCount: 0,
            ReplyCount: 0,
            CanCancel: true,
            IsDeleted: false,
            Replies: [],
          },
          res.data,
        );

        // 评论完将新添加评论展示出来：滚动到顶部
        this.commentList.unshift(newComment);
        const container = this.$refs.commentScrollAreaRef;
        container.scrollTop = 0;

        this.totalCommentCount += 1;

        setTimeout(() => {
          // 调接口成功后清空输入框内容
          onSucceed();
        }, 400);
      } catch (error) {
        console.log(error);
        onFail();
      }
    },
    onScroll(e) {
      const { deltaY } = e;
      if (
        deltaY < 0 ||
        !this.commentList ||
        !this.commentList.length ||
        this.isLoading ||
        this.hasLoadedAll
      ) {
        // 滚向顶部时、没有数据时、正在加载数据时、及全部加载完时，滚动无需处理
        return;
      }
      requestAnimationFrame(this.scrollHanlder);
    },
    scrollHanlder() {
      const container = this.$refs.commentScrollAreaRef;
      const lastItem = container.querySelector(
        '.section-comment-with-replies:last-child',
      );
      // 提前 300px 获取下一页数据
      scrollPaging(container, lastItem, 300, this.fetchPageData);
    },
  },
};
</script>

<style lang="scss" scoped>
.teld-comment {

  .section-comment-with-replies:last-child {
    border-bottom: none;
  }
}
</style>
